package com.tianji.learning.service.impl;

import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseFullInfoDTO;
import com.tianji.api.dto.leanring.LearningLessonDTO;
import com.tianji.api.dto.leanring.LearningRecordDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.LearningRecordFormDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.SectionType;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.tianji.learning.service.ILearningRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.learning.utils.LearningRecordDelayTaskHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 学习记录表 服务实现类
 * </p>
 *
 * @author 晚风
 * @since 2023-09-20
 */
@Service
@RequiredArgsConstructor
public class LearningRecordServiceImpl extends ServiceImpl<LearningRecordMapper, LearningRecord> implements ILearningRecordService {

    private final ILearningLessonService lessonService;
    private final CourseClient courseClient;
    private final LearningRecordDelayTaskHandler taskHandler;

    @Override
    public LearningLessonDTO queryLearningRecordByCourse(Long courseId) {
        // 1. 获取用户id
        Long userId = UserContext.getUser();
        // 2. 查询课程表，条件用户id，课程id
        LearningLesson lesson = lessonService.lambdaQuery().eq(LearningLesson::getCourseId, courseId).eq(LearningLesson::getUserId, userId).one();
        if (lesson == null) {
            throw new BizIllegalException("未买购该课程");
        }
        // 3. 查询学习记录 条件 用户id ， 课表id
        List<LearningRecord> recordList = this.lambdaQuery().eq(LearningRecord::getLessonId, lesson.getId()).eq(LearningRecord::getUserId, userId).list();
        // 4. 封装结果返回
        LearningLessonDTO dto = new LearningLessonDTO();
        dto.setId(lesson.getId()); // 课表id
        List<LearningRecordDTO> dtoList = BeanUtils.copyList(recordList, LearningRecordDTO.class);
        dto.setRecords(dtoList);  // 学习过小节的记录
        dto.setLatestSectionId(lesson.getLatestSectionId()); // 最近学习小节id
        return dto;
    }

    @Override
    public void addLearningRecord(LearningRecordFormDTO dto) {
        // 1. 获取当前用户id
        Long userId = UserContext.getUser();
        boolean isFinished = false; // 本小姐是否学完
        // 2. 处理学习记录
        if (dto.getSectionType().equals(SectionType.VIDEO)){
            // 2.1 提交视频播放记录
            isFinished = handleVideoRecord(userId,dto);
        }else {
            // 2.2 提交考试记录
            isFinished = handleExamRecord(userId,dto);
        }
        // 3. 处理课表数据
        if (!isFinished){
            return; // 如果本小节不是第一次学完，不用处理课表数据
        }
        handleLessonData(dto);

    }

    // 处理课表相关数据
    private void handleLessonData(LearningRecordFormDTO dto) {
        // 1. 查询课表learning_lesson 条件 lesson_id主键
        LearningLesson lesson = lessonService.getById(dto.getLessonId());
        if (lesson == null){
            throw new BizIllegalException("课表不存在");
        }
        // 2. 判断是否是第一次学完
        boolean allFinished = false; // 判断是否学完该课程全部小节
            // 3. 远程调用课程服务  得到课程信息  小节总数
            CourseFullInfoDTO cinfo = courseClient.getCourseInfoById(lesson.getCourseId(), false, false);
            if (cinfo == null){
                throw new BizIllegalException("课程不存在");
            }
            Integer sectionNum = cinfo.getSectionNum(); // 当前课程的总节数
            // 4. 如果isFinished为true，本小节是第一次学完，判断该用户对该课程的的所有小节是否全部学完
            Integer learnedSections = lesson.getLearnedSections(); //获取当前用户对该课程已学的小节数
            allFinished = learnedSections + 1 >= sectionNum;
        // 5. 更新课表数据
        lessonService.lambdaUpdate()
                .set(lesson.getStatus() == LessonStatus.NOT_BEGIN, LearningLesson::getStatus, LessonStatus.LEARNING)
                .set(allFinished, LearningLesson::getStatus, LessonStatus.FINISHED)
                .set(LearningLesson::getLatestSectionId, dto.getSectionId())
                .set(LearningLesson::getLatestLearnTime, dto.getCommitTime())
                .setSql("learned_sections = learned_sections + 1")
                .eq(LearningLesson::getId, lesson.getId())
                .update();
    }

    // 处理视频播放记录
    private boolean handleVideoRecord(Long userId, LearningRecordFormDTO dto) {
        LearningRecord learningRecord = queryOldRecord(dto.getLessonId(),dto.getSectionId());
        // 查询旧的学习记录
//        LearningRecord learningRecord = this.lambdaQuery()
//                .eq(LearningRecord::getLessonId, dto.getLessonId())
//                .eq(LearningRecord::getUserId, userId)
//                .eq(LearningRecord::getSectionId, dto.getSectionId()).one();

        if (learningRecord == null){
            LearningRecord record = BeanUtils.copyBean(dto, LearningRecord.class);
            record.setUserId(userId);
            boolean result = this.save(record);
            if (!result){
                throw new DbException("新增学习记录失败");
            }
            return false;
        }
        // 判断存在则更新学习记录，learning_record 更新moment
        // 判断小节是否是第一次学完，isFinished为true代表第一次学完
        boolean isFinished = !learningRecord.getFinished() && ((dto.getMoment() * 2) >= dto.getDuration());
        if (!isFinished){
            LearningRecord record = new LearningRecord();
            record.setId(learningRecord.getId());
            record.setMoment(learningRecord.getMoment());
            record.setLessonId(learningRecord.getLessonId());
            record.setSectionId(learningRecord.getSectionId());
            record.setFinished(learningRecord.getFinished());
            taskHandler.addLearningRecordTask(record);
            return false;
        }
        boolean result = this.lambdaUpdate()
                .set(LearningRecord::getMoment, dto.getMoment())
                .set(isFinished, LearningRecord::getFinished, true)
                .set(isFinished, LearningRecord::getFinishTime, dto.getCommitTime())
                .eq(LearningRecord::getId, learningRecord.getId()).update();
        if (!result){
            throw new DbException("新增观看视频记录失败");
        }
        // 清理redis
        taskHandler.cleanRecordCache(learningRecord.getLessonId(), learningRecord.getSectionId());
        return isFinished;
    }

    private LearningRecord queryOldRecord(Long lessonId, Long sectionId) {
        // 1.查询缓存
        LearningRecord cache = taskHandler.readRecordCache(lessonId, sectionId);
        if (cache != null){
            // 2.命中直接返回
            return cache;
        }
        // 3.未命中，查询db
                LearningRecord dbRecord = this.lambdaQuery()
                .eq(LearningRecord::getLessonId, lessonId)
                .eq(LearningRecord::getSectionId, sectionId).one();
        if (dbRecord == null) {
            return null;
        }
        // 4.写入缓存
        taskHandler.writeRecordCache(dbRecord);
        // 5.返回数据
        return dbRecord;
    }

    // 处理考试状态
    private boolean handleExamRecord(Long userId, LearningRecordFormDTO dto) {
        // 将dto转换成po
        LearningRecord record = BeanUtils.copyBean(dto, LearningRecord.class);
        record.setUserId(userId);
        record.setFinished(true); // 提交考试记录，表示已学完
        record.setFinishTime(dto.getCommitTime());
        // 保存学习记录 learning_record
        boolean result = this.save(record);
        if (!result){
            throw new DbException("新增考试记录失败");
        }
        return true;
    }
}
